/**
 * Created by huangying on 16/11/6.
 */
var areaName = "";
window.onload = function () {
    $('.loading').hide();
    infomation();
    initComplexArea('seachprov', 'seachcity', 'seachdistrict', area_array, sub_array, '0', '0', '0');
    $.ms_DatePicker({
        YearSelector: "#select_year",
        MonthSelector: "#select_month",
        DaySelector: "#select_day"
    });
};
//=======================================显示个人信息=======================================//
function infomation() {
    $.get(url_link + 'users/' + user_id, function (data) {
        var obj = JSON.parse(data);
        if (obj.code == 0) {
            $('#o_n_n').html(obj.data.nickname);
            $('#o_s_t').html(obj.data.sign);
        }
    })
}
//=======================================显示城市省份信息=======================================//
//得到地区码
function getAreaID() {
    var area = 0;
    if ($("#seachdistrict").val() != "0") {
        area = $("#seachdistrict").val();
    } else if ($("#seachcity").val() != "0") {
        area = $("#seachcity").val();
    } else {
        area = $("#seachprov").val();
    }
    return area;
}
function showAreaID() {
    //地区码
    var areaID = getAreaID();
    //地区名
    areaName = getAreaNamebyID(areaID);
}
//根据地区码查询地区名
function getAreaNamebyID(areaID) {
    var areaName = "";
    if (areaID.length == 2) {
        areaName = area_array[areaID];
    } else if (areaID.length == 4) {
        var index1 = areaID.substring(0, 2);
        areaName = area_array[index1] + " " + sub_array[index1][areaID];
    } else if (areaID.length == 6) {
        var index1 = areaID.substring(0, 2);
        var index2 = areaID.substring(0, 4);
        areaName = area_array[index1] + " " + sub_array[index1][index2] + " " + sub_arr[index2][areaID];
    }
    return areaName;
}
//=======================================修改密码=======================================//
$(document).on('click', '#save-pw-button', function () {
    var old_pwd = $('#old_pwd').val();
    var new_pwd = $('#new_pwd').val();
    var new_pwd_again = $('#new_pwd_again').val();
    var pwd_preg = /^[a-zA-Z0-9_-]{6,16}$/;
    if (!old_pwd) {
        layer.msg("请输入您的旧密码!")
    } else if (!new_pwd) {
        layer.msg("请输入您的新密码!")
    } else if (!new_pwd_again) {
        layer.msg("请再次输入您的新密码!")
    } else if (!(pwd_preg.test(new_pwd))) {
        layer.msg("新密码输入格式错误!")
    } else if (old_pwd == new_pwd) {
        layer.msg("旧密码与新密码相同!")
    } else if (new_pwd != new_pwd_again) {
        layer.msg("两次密码输入不同!")
    } else {
        $.ajax({
            type: 'get',
            url: url_link + 'users',
            data: {
                user_id: user_id,
                password: old_pwd,
                newPassword: new_pwd
            },
            success: function (data) {
                var obj = JSON.parse(data);
                if (obj.code == 0) {
                    layer.msg("修改密码成功!")
                }
            }
        });
    }
})
//=======================================图片预览=======================================//
function setImagePreview(file,id) {
    $('.loading').show();
    _id = id;
    var prevDiv = document.getElementById("localImag");
    if (file.files && file.files[0]) {
        var postfix = file.files[0].name.split('.').pop();
        if(postfix!="jpg"&&postfix!="gif"&&postfix!="png"&&postfix!="jpeg"){
            $('.loading').hide();
            layer.msg("上传仅支持：jpg,gif,png,jpeg格式")
        }else{
            var reader = new FileReader();
            reader.onload = function (evt) {
                //上传又拍云
                var ext = '.' + file.files[0].name.split('.').pop();
                var config = {
                    bucket: 'motorcycle',
                    expiration: parseInt((new Date().getTime() + 3600000) / 1000),
                    // 尽量不要使用直接传表单 API 的方式，以防泄露造成安全隐患
                    form_api_secret: '0jWegIsJu9xVxJMrgp4ydONAxok='
                };
                var instance = new Sand(config);
                instance.upload("headIcon/"+parseInt((new Date().getTime() + 3600000) / 1000) + ext);
                prevDiv.innerHTML = '<img id="preview" src=" " width="200" height="200" style="display: block;border: 1px solid #999999;border-radius: 50%;"/>';
            };
            reader.readAsDataURL(file.files[0]);
        }

    } else {
        $('.loading').hide();
    }


}
//=======================================上传图片=======================================//
//获取又拍云图片路径
document.addEventListener('uploaded', function (e) {
    for (var key in e.detail) {
        if (key === 'path') {
            var img_url = '';
            img_url = "http://motorcycle.b0.upaiyun.com" + e.detail[key]+"!/quality/80/fw/500";
            $('#preview').attr('src', img_url);
            $('.loading').hide();
        }
    }
});
//=======================================保存个人信息=======================================//
$(document).on('click', '#save_info_button', function () {
    var img_info = $('#preview').attr('src');
    var name_info = $('#n_n').val();
    var sign_info = $('#s_t').val();
    var city_info_province = $('#seachprov option:selected').val();
    var birthday_info_year = $('#select_year option:selected').val();
    var birthday_info_mouth = $('#select_month option:selected').val();
    var birthday_info_day = $('#select_day option:selected').val();
    var birthday_info = birthday_info_year + "-" + birthday_info_mouth + "-" + birthday_info_day;
    var sex_info = $('input[name="sex"]:checked').val();


    var name_preg = /^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,8}$/;
    var birthday_preg = /^(19|20)\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$/;


    if (name_info && !(name_preg.test(name_info))) {
        layer.msg("您的昵称格式有误!")
    } else if (birthday_info != "0-0-0" && !(birthday_preg.test(birthday_info))) {
        layer.msg("您的生日格式有误!")
    }  else {
        if (city_info_province != 0) {
            showAreaID();
        }
        if(img_info=="../../image/base/none.png"){
            img_info="";
        }
        if (birthday_info == "0-0-0") {
            birthday_info = '';
        }else{
            birthday_info=birthday_info.replace(/-/g,"/")
        }
        data_motocycle = {
            nickname: name_info,
            avatar: img_info,
            sign: sign_info,
            area: areaName,
            birth: birthday_info,
            sex: sex_info
        };
        $.ajax({
            type: 'PUT',
            url: url_link + 'users/' + user_id,
            data: data_motocycle,
            success: function (data) {
                var obj = JSON.parse(data);
                if (obj.code == 0) {
                    layer.msg("修改成功!页面跳转中...");
                    setTimeout(function () {
                        window.location.href = "../../index.html";
                    }, 3000)
                }
            }
        })
    }
})